<?php
/**
 * ebiz front
 * 
 * DBUtil
 *  
 * @author allen
 *  
 */

require_once('../conf/config.php'); 

class DBUtil
{
	
	private $db_r;
	private $db_w;
	
    public static $db_r_execute_num; //count the DB read connection number
    public static $db_w_execute_num; //count the DB write connection number
	   
	public function DBUtil(){
		
        $dsn_m = "mysql:host=". DB_HOST_M .";dbname=" . DB_PREFIX.'_'.DB_NAME_M;
        $dsn_s = "mysql:host=". DB_HOST_S .";dbname=" . DB_PREFIX.'_'.DB_NAME_S;
        //db_w
        $this->db_w = new PDO($dsn_m, DB_USERNAME_M, DB_PASSWORD_M);
        $this->db_w->query("SET NAMES utf8;");//set the DB read and write is utf-8 model
        //db_r
		$this->db_r = new PDO($dsn_s, DB_USERNAME_S, DB_PASSWORD_S);
		$this->db_r->query("SET NAMES utf8;");
		
		

	}
	
	function ExecuteQuery($sql,$paraArray= array(),$del=0){	
		try{  
			if(empty($this->db_w)){				
				print_r ('databace error !');exit;
			}
			
	        if ($GLOBALS["debug"] == 1 || DEBUG_INFO == 1){
				DBUtil::$db_w_execute_num = DBUtil::$db_w_execute_num + 1;
			}
			
			$stmt = $this->db_w->prepare($sql);
			$result = $stmt->execute($paraArray);
			if($del == 1){
				return $result;
			}
			if( preg_match( '/^insert /i', trim( $sql ) ) )
			     return $this->db_w->lastInsertId();
			else 
			     return $result;
		}catch (Exception $e){
			echo $e->getMessage();
			exit();
		}
	}
	
	function SelectData($sql,$paraArray=array()){
		
        if ($GLOBALS["debug"] == 1 || DEBUG_INFO == 1){
            DBUtil::$db_r_execute_num = DBUtil::$db_r_execute_num + 1;
        }
		$data = array();
		$stmt =  $this->db_r->prepare($sql);
		$stmt -> execute($paraArray);
		$stmt -> setFetchMode(PDO::FETCH_ASSOC);
		foreach ($stmt as $key => $row) {
			$data[$key] = $row;
		}
		return $data;
	}

    /**
     * Use for select last found rows number
     *
     * @author by M.Wang
     * @return int
     */
    public function getLastFoundRows(){
        return self::SelectData( 'SELECT FOUND_ROWS() AS ROWS', array() );
    }
    
}

